package com.np.media1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioManager;
import android.media.AudioMetadata;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.io.IOException;

public class SurfaceViewActivity extends AppCompatActivity implements View.OnClickListener {

    SurfaceView surfaceView1;
    MediaPlayer mediaPlayer1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_surface_view);

        surfaceView1 = findViewById(R.id.surfaceView1);
        findViewById(R.id.btnPlay).setOnClickListener(this);
        findViewById(R.id.btnPause).setOnClickListener(this);
        findViewById(R.id.btnStop).setOnClickListener(this);

        init();
    }

    @Override
    public void onClick(View v) {
        if (R.id.btnStop == v.getId()) {
            stop();
        } else if (R.id.btnPlay == v.getId()) {
            if (!mediaPlayer1.isPlaying())
                play();
        } else if (R.id.btnPause == v.getId()) {
            pause();
        }
    }

    private void init() {
        mediaPlayer1 = new MediaPlayer();
        surfaceView1.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                play();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

            }
        });
    }

    private void play() {
        String path = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
        try {
            mediaPlayer1.reset();
            mediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer1.setDataSource(this, Uri.parse(path));
            mediaPlayer1.setDisplay(surfaceView1.getHolder());
            mediaPlayer1.prepare();
            mediaPlayer1.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void stop() {
        if (mediaPlayer1.isPlaying()) {
            mediaPlayer1.stop();
        }
    }

    private void pause() {
        if (mediaPlayer1.isPlaying()) {
            mediaPlayer1.pause();
        } else {
            mediaPlayer1.start();
        }
    }
}